Option Strict Off
Option Explicit On
Imports VB = Microsoft.VisualBasic
Imports DxVBLibA
Imports SlimDX
Imports System
Imports System.IO
Module D3DUtil
	
	
	'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
	'
	'  Copyright (C) 2000 Microsoft Corporation.  All Rights Reserved.
	'
	'  File:       D3DUtil.Bas
	'  Content:    VB D3DFramework utility module
	'
	'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
	
	' DOC:  Use with
	' DOC:        D3DAnimation.cls
	' DOC:        D3DFrame.cls
	' DOC:        D3DMesh.cls
	' DOC:        D3DSelectDevice.frm (optional)
	' DOC:
	' DOC:  Short list of usefull functions
	' DOC:        D3DUtil_Init                  first call to framework
	' DOC:        D3DUtil_LoadFromFile          loads an x-file
	' DOC:        D3DUtil_SetupDefaultScene     setup a camera lights and materials
	' DOC:        D3DUtil_SetupCamera           point camera
	' DOC:        D3DUtil_SetupMediaPath        set directory to load textures from
	' DOC:        D3DUtil_PresentAll            show graphic on the screen
	' DOC:        D3DUtil_ResizeWindowed        resize for windowed modes
	' DOC:        D3DUtil_ResizeFullscreen      resize to fullscreen mode
	' DOC:        D3DUtil_CreateTextureInPool   create a texture
	
	
	
	
	' DOC: DXLockArray8 & DXUnlockArray8
	' DOC:
	' DOC: These are Helper functions that allow textures, vertex buffers, and index buffers
	' DOC: to look like VB arrays to the VB user.
	' DOC: It is imperative that Lock be matched with unlock or undefined behaviour may result
	' DOC: It is imperative that DXLockarray8 be matched with DXUnlockArray8 or undefined behaviour may result
	' DOC:
	' DOC: DXLockArray8
	' DOC:       resource    - can be Direct3DTexture8,Direct3dVertexBuffer8, or a Direct3DIndexBuffer
	' DOC:       addr        - is the number provide by IndexBuffer.Lock,Testure.Lock etc
	' DOC:       arr()       - a VB array that can be used to shadow video memory
	' DOC: DXUnlockArray8
	' DOC:       resource    - the resource passed to DXLockArray8
	' DOC:       arr()       - the VB array passed to DXLockArray8
	' DOC:
	' DOC: Example
	' DOC:           dim m_vertBuff as Direct3DVertexBuffer  'we assume this has been created
	' DOC:           dim m_vertCount as long                 'we assume this has been set
	' DOC:
	' DOC:           Dim addr As Long                        'will holds the address the D3D
	' DOC:                                                   'managed memory
	' DOC:           dim verts() as D3DVERTEX                'array that we want to point to
	' DOC:                                                   'D3D managed memory
	' DOC:
	' DOC:           redim verts(m_vertCount)                'ensure the size is large
	' DOC:                                                   'enough for the data and has
	' DOC:                                                   'as many dimensions as needed
	' DOC:                                                   '(1d for vertex buffer, 2d for
	' DOC:                                                   ' surfaces, 3d for volumes)
	' DOC:                                                   'resize the array once and
	' DOC:                                                   'reuse for frequent manipulation
	' DOC:
	' DOC:           m_vertBuff.Lock 0, Len(verts(0)) * m_vertCount, addr, 0
	' DOC:
	' DOC:           DXLockArray8 m_vertBuff, addr, verts
	' DOC:
	' DOC:           for i = 0 to m_vertCount-1
	' DOC:               verts(i).x=i ' or what ever you want to dow with the data
	' DOC:           next
	' DOC:
	' DOC:           DXUnlockArray8 m_vertBuff, verts
	' DOC:
	' DOC:           VB.Unlock
	'
    'Public Declare Function DXLockArray8 Lib "dx8vb.dll" (ByVal resource As Direct3DResource8, ByVal addr As Integer, ByRef arr() As D3DVERTEX) As Integer
    'Public Declare Function DXUnlockArray8 Lib "dx8vb.dll" (ByVal resource As Direct3DResource8, ByRef arr() As D3DVERTEX) As Integer
	
	
	
	'DOC: Texture Load data applied to all textures
	'DOC: can be accessed by g_TextureSampling variable
    Public Structure TextureParams
        Dim enable As Boolean 'enable texture sampling
        Dim width As Integer 'default width of textures
        Dim height As Integer 'default height of textures
        Dim miplevels As Integer 'default number of miplevels
        Dim mipfilter As Direct3D9.Filter 'default mipmap filter
        Dim filter_Renamed As Direct3D9.Filter 'default texture filter
        Dim fmt As SlimDX.Direct3D9.Format 'default texture format
        Dim fmtTrans As SlimDX.Direct3D9.Format 'default transparent format
        Dim colorTrans As Integer 'default transparent color
    End Structure
	
	
	'DOC: Rotate key used in conjuction with the CD3DAnimation class
	Public Structure D3DROTATEKEY
		Dim time As Integer
		Dim nFloats As Integer
        Dim quat As SlimDX.Quaternion
	End Structure
	
	'DOC: Scale or Translate key used in conjuction with the CD3DAnimation class
    Public Structure Vector3KEY
        Dim time As Integer
        Dim nFloats As Integer
        Dim vec As SlimDX.Vector3
        Public Function GetPtr() As IntPtr
            Dim p As IntPtr = System.Runtime.InteropServices.Marshal.AllocHGlobal(SizeBytes)
            System.Runtime.InteropServices.Marshal.StructureToPtr(Me, p, True)
            Return p
        End Function
        Public Function SizeBytes() As Integer
            Return System.Runtime.InteropServices.Marshal.SizeOf(Me)
        End Function
    End Structure

    'DOC: Pick record using with CD3DPick class
    Public Structure D3D_PICK_RECORD
        Dim hit() As Direct3D9.IntersectInformation
        Dim triFaceid As Integer
        Dim a As Single
        Dim b As Single
        Dim dist As Single
        Public Sub Init()
            ReDim hit(100)
            hit(0) = New Direct3D9.IntersectInformation
        End Sub
    End Structure

    'DOC: see D3DUtil_Timer
    Public Enum TIMER_COMMAND
        TIMER_RESET = 1 '- to reset the timer
        TIMER_START = 2 '- to start the timer
        TIMER_STOP = 3 '- to stop (or pause) the timer
        TIMER_ADVANCE = 4 '- to advance the timer by 0.1 seconds
        TIMER_GETABSOLUTETIME = 5 '- to get the absolute system time
        TIMER_GETAPPTIME = 6 '- to get the current time
        TIMER_GETELLAPSEDTIME = 7 '- to get the ellapsed time
    End Enum


    'DOC: Info on a per texture basis
    Private Structure TexPoolEntry
        Dim Name As String
        Dim tex As SlimDX.Direct3D9.Texture
        Dim nextDelNode As Integer
    End Structure



    '------------------------------------------------------------------
    ' DOC: Usefull globals
    '------------------------------------------------------------------


    Public g_bDontDrawTextures As Boolean ' Debuging switches
    Public g_bClipMesh As Boolean ' Debuging switches
    Public g_bLoadSkins As Boolean ' Debuging switches
    Public g_bLoadNoAlpha As Boolean ' Debuging switches

    ' view frustrum (use as read only)
    Public g_fov As Single ' view frustrum field of view
    Public g_aspect As Single ' view frustrum aspect ratio
    Public g_znear As Single ' view frustrum near plane
    Public g_zfar As Single ' view frustrom far plane

    ' Matrices (use as read only)
    Public g_identityMatrix As New Matrix ' Filled with Identity Matrix after D3DUtil_Init
    Public g_worldMatrix As New Matrix ' Filled with current world matrix
    Public g_viewMatrix As New Matrix ' Filled with current view matrix
    Public g_projMatrix As New Matrix ' Filled with current projection matrix

    ' Clipplanes: use to ComputeClipPlanes to initialize
    ' helpfull for view frustrum culling
    Public g_ClipPlanes() As Plane ' Clipplane plane array
    Public g_numClipPlanes As Integer ' Number of clip planes in g_ClipPlanes

    Public light0 As New Direct3D9.Light  ' light type usefull in imediate pane
    Public light1 As New Direct3D9.Light ' light type usefull in imediate pane

    Public g_TextureSampling As TextureParams ' defines how CreateTextureInPool sample textures

    Public g_TextureLoadCallback As Object ' object that implements LoadTextureCallback(sName as string) as Direct3dTexture8
    Public g_bUseTextureLoadCallback As Boolean ' enables disables callback

    Public g_mediaPath As String ' Path to media and texture
    ' read/write - must have ending backslash
    ' best to use SetMediaPath to initialize



    '------------------------------------------------------------------
    ' Global constants
    '------------------------------------------------------------------

    Public Const g_pi As Double = 3.1415
    Public Const g_InvertRotateKey As Boolean = True 'flag to turn on fix for animation key problem
    Public Const D3DFVF_VERTEX As Integer = Direct3D9.VertexFormat.Position _
                                            Or Direct3D9.VertexFormat.Normal _
                                            Or Direct3D9.VertexFormat.Texture0

    '------------------------------------------------------------------
    ' Locals
    '------------------------------------------------------------------

    ' TexturePool Mangement data. see..
    '  D3DUTIL_LoadTextureIntoPool
    '  D3DUTIL_AddTextureToPool
    '  D3DUTIL_ReleaseTextureFromPool
    '  D3DUTIL_ReleaseAllTexturesFromPool
    '
    Dim m_texPool() As TexPoolEntry
    Dim m_maxPool As Integer
    Dim m_nextEmpty As Integer
    Dim m_firstDel As Integer

    Const kGrowSize As Short = 10


    '------------------------------------------------------------------
    ' Functions
    '------------------------------------------------------------------

    '-----------------------------------------------------------------------------
    'DOC: D3DUtil_SetupDefaultScene
    'DOC:
    'DOC: helper function that initializes some default lighting and render states
    'DOC:
    'DOC: remarks:
    'DOC:   sets defaults for
    'DOC:   g_fov, g_aspect, g_znear, g_zfar
    'DOC:   g_identityMatrix, g_projMatrix, g_ViewMatrix, g_worldMatrix
    'DOC:   set device state for project view and world matrices
    'DOC:   set device state for 2 directional lights (0 and 1)
    'DOC:   set device state for a default grey material
    '-----------------------------------------------------------------------------

    Public Sub D3DUtil_SetupDefaultScene()

        g_fov = g_pi / 4
        g_aspect = 1
        g_znear = 1
        g_zfar = 3000

        If g_lWindowHeight <> 0 And g_lWindowWidth <> 0 Then g_aspect = g_lWindowWidth / g_lWindowHeight
        g_identityMatrix = Matrix.Identity
        g_projMatrix = SlimDX.Matrix.PerspectiveFovLH(g_fov, g_aspect, g_znear, g_zfar)

        g_dev.SetTransform(Direct3D9.TransformState.Projection, g_projMatrix)

        ' DxVBLibA.D3DXMATH_MATRIX.D3DXMatrixLookAtLH(g_viewMatrix, vec3(0.0!, 0.0!, 0.0!), vec3(0.0!, 0.0!, 1.0!), vec3(0.0!, 1.0!, 0.0!))
        g_viewMatrix = Matrix.LookAtLH(New Vector3(0.0!, 0.0!, 0.0!), New Vector3(0.0!, 0.0!, 1.0!), New Vector3(0.0!, 1.0!, 0.0!))

        g_dev.SetTransform(Direct3D9.TransformState.View, g_viewMatrix)
        g_dev.SetTransform(Direct3D9.TransformState.World, g_identityMatrix)

        'default light0
        '  light0.Ambient = ColorValue4(1, 0.1, 0.1, 0.1)
        Dim c As New Color4(0.5, 0.5, 0.3, 0.5)
        light0.Diffuse = c
        light0.Ambient = c
        light0.Specular = c
        light0.Type = Direct3D9.LightType.Directional 'DxVBLibA.CONST_D3DLIGHTTYPE.D3DLIGHT_DIRECTIONAL
        light0.Range = 1000
        light0.Direction = New Vector3(-1, 1, 1)
        light0.Direction.Normalize()


        'DxVBLibA.D3DXMATH_VECTOR3.D3DXVec3Normalize((light0.Direction), light0.Direction)

        g_dev.SetLight(0, light0)
        g_dev.EnableLight(0, True) 'true

        'default light1

        light1.Ambient = ColorValue4(1, 0.3, 0.3, 0.3)
        light1.Diffuse = ColorValue4(1, 1, 1, 1)
        light1.Type = Direct3D9.LightType.Directional 'DxVBLibA.CONST_D3DLIGHTTYPE.D3DLIGHT_DIRECTIONAL
        light1.Range = 1000
        light1.Direction = New Vector3(1, -1, -1)
         
        light1.Direction = Vector3.Normalize(light1.Direction)
        'DxVBLibA.D3DXMATH_VECTOR3.D3DXVec3Normalize((light1.Direction), light1.Direction)



        'set first material
        Dim material0 As New Direct3D9.Material ' Direct3d9.Material
        material0.Ambient = ColorValue4(1, 0.2, 0.2, 0.2)
        material0.Diffuse = ColorValue4(1, 0.5, 0.5, 0.5)
        material0.Power = 1

        ' g_dev.SetMaterial(material0)


        With g_dev

            ' Set up the default texture states
            '   g_dev.SetTextureStageState 0, D3DTSS_COLOROP, D3DTOP_SELECTARG1
            '   g_dev.SetTextureStageState 0, D3DTSS_COLORARG1, D3DTA_TEXTURE
            .SetTextureStageState(0, Direct3D9.TextureStage.AlphaOperation, Direct3D9.TextureOperation.SelectArg1)
            ' .SetTextureStageState(0, Direct3D9.TextureStage.AlphaArg1 Direct3D9.TextureTransformFlags.ColorArg1)
            .SetTextureStageState(0, Direct3D9.TextureStage.AlphaArg0, Direct3D9.TextureFilter.Linear)
            ' .SetTextureStageState(0, 16, Direct3D9.TextureFilter.Linear)

            'g_dev.SetTextureStageState(0, DxVBLibA.CONST_D3DTEXTURESTAGESTATETYPE.D3DTSS_ALPHAOP, DxVBLibA.CONST_D3DTEXTUREOP.D3DTOP_SELECTARG1)
            'g_dev.SetTextureStageState(0, DxVBLibA.CONST_D3DTEXTURESTAGESTATETYPE.D3DTSS_ALPHAARG1, DxVBLibA.CONST_D3DTAFLAGS.D3DTA_TEXTURE)
            'g_dev.SetTextureStageState(0, DxVBLibA.CONST_D3DTEXTURESTAGESTATETYPE.D3DTSS_MINFILTER, DxVBLibA.CONST_D3DTEXTUREFILTERTYPE.D3DTEXF_LINEAR)
            'g_dev.SetTextureStageState(0, DxVBLibA.CONST_D3DTEXTURESTAGESTATETYPE.D3DTSS_MAGFILTER, DxVBLibA.CONST_D3DTEXTUREFILTERTYPE.D3DTEXF_LINEAR)

            .SetRenderState(Direct3D9.RenderState.DitherEnable, True)
            .SetRenderState(Direct3D9.RenderState.Ambient, c.ToArgb)
            .SetRenderState(Direct3D9.RenderState.ClipPlaneEnable, True)
            .SetRenderState(Direct3D9.RenderState.Lighting, True)
            .SetRenderState(Direct3D9.RenderState.ZEnable, True)
            .SetRenderState(Direct3D9.RenderState.ShadeMode, Direct3D9.ShadeMode.Gouraud)


            '         .SetRenderState(DxVBLibA.CONST_D3DRENDERSTATETYPE.D3DRS_DITHERENABLE, 1)
            'Call .SetRenderState(DxVBLibA.CONST_D3DRENDERSTATETYPE.D3DRS_AMBIENT, &H10101010)
            'Call .SetRenderState(DxVBLibA.CONST_D3DRENDERSTATETYPE.D3DRS_CLIPPING, 1) 'CLIPPING IS ON
            'Call .SetRenderState(Direct3D9.RenderState.Lighting, 1) 'LIGHTING IS ON
            'Call .SetRenderState(Direct3D9.RenderState.ZEnable, 1) 'USE ZBUFFER
            'Call .SetRenderState(Direct3D9.RenderState.ShadeMode, DxVBLibA.CONST_D3DSHADEMODE.D3DSHADE_GOURAUD)
        End With

    End Sub

    '-----------------------------------------------------------------------------
    'DOC: D3DUtil_SetupCamera
    'DOC: Params
    'DOC:   fromV   world space vector of camera position
    'DOC:   toV     world space vector of position camera is looking toward
    'DOC:   upV     world space vector of cameras up direction
    'DOC: Remarks
    'DOC:   effects g_viewMatrix and device ViewMatrix state
    'DOC:   Make sure upV is different than the direction of sight
    '-----------------------------------------------------------------------------
    Sub D3DUtil_SetupCamera(fromV As Vector3, toV As Vector3, upV As Vector3)

        g_viewMatrix = Matrix.LookAtLH(fromV, toV, upV)

        ' DxVBLibA.D3DXMATH_MATRIX.D3DXMatrixLookAtLH(g_viewMatrix, fromV, toV, upV)
        g_dev.SetTransform(Direct3D9.TransformState.View, g_viewMatrix)

    End Sub


    '-----------------------------------------------------------------------------
    'DOC: D3DUtil_ClearAll
    'DOC: Params
    'DOC:   col     color to clear the backbuffer
    'DOC: Remarks
    'DOC:   convenience function that assumes a rendertarget with a zbuffer and
    'DOC:   no stencil
    '-----------------------------------------------------------------------------

    Sub D3DUtil_ClearAll(ByRef Col As Integer)
        Try
            If Not g_dev Is Nothing Then
                g_dev.Clear((Direct3D9.ClearFlags.Target _
                       Or (Direct3D9.ClearFlags.ZBuffer Or Direct3D9.ClearFlags.Stencil)), Col, 1.0!, 0)
            End If
            ' g_dev.Clear(0, 0, DxVBLibA.CONST_D3DCLEARFLAGS.D3DCLEAR_TARGET Or DxVBLibA.CONST_D3DCLEARFLAGS.D3DCLEAR_ZBUFFER, Col, 1, 0)
        Catch ex As Exception

            Debug.Print("D3DUtil_ClearAll Error")
            DestroyDeviceObjects()

        End Try

    End Sub




    '-----------------------------------------------------------------------------
    'DOC: D3DUtil_PresentAll
    'DOC: Params
    'DOC:   hwnd    hwnd to present to
    'DOC: Remarks
    'DOC:   Convience function that presents the contents of a backbuffer to an hwnd
    'DOC:
    '-----------------------------------------------------------------------------
    Sub D3DUtil_PresentAll(ByRef hwnd As Integer)

        Try

            g_dev.EndScene()
            g_dev.Present()

            'g_dev.Present(0, 0, hwnd, 0)
        Catch ex As Exception
            Debug.Print(ex.Message & " Device.present (PresentAll)")
        End Try



        Try
            'some video cards leave the divide by zero flag set after Present or EndScene
            'here we force a divide by zero to force vb to reset the flag so the next
            'math operation doesnt give a divide by zero error
            Dim Dummy As Single
            Dummy = Dummy / 0
        Catch ex As Exception

        End Try



    End Sub


    '-----------------------------------------------------------------------------
    'DOC: ColorValue4
    'DOC: Params
    'DOC:   a r g b   values valid between 0.0 and 1.0
    'DOC: Return Value
    'DOC:   a filled D3DCOLORVALUE type
    '-----------------------------------------------------------------------------
    Function ColorValue4(a As Single, r As Single, g As Single, b As Single) As SlimDX.Color4
        Return New SlimDX.Color4(a, r, g, b)
    End Function

    Sub SetProjParams(ByRef fFOV As Single, ByRef fAspect As Single, ByRef fNearPlane As Single, ByRef fFarPlane As Single)
        '   // Set attributes for the projection matrix
        '   m_fFOV        = fFOV;
        '   m_fAspect     = fAspect;
        '   m_fNearPlane  = fNearPlane;
        '   m_fFarPlane   = fFarPlane;

        '  D3DXMatrixPerspectiveFovLH( &m_matProj, fFOV, fAspect, fNearPlane, fFarPlane );
        '}


    End Sub

    '-----------------------------------------------------------------------------
    'DOC: Vec2
    'DOC: Params
    'DOC:   x y z   vector values
    'DOC: Return Value
    'DOC:   a filled Vector3 type
    '-----------------------------------------------------------------------------
    Function vec2(x As Single, y As Single) As Vector2
        Return New Vector2(x, y)
    End Function


    '-----------------------------------------------------------------------------
    'DOC: Vec3
    'DOC: Params
    'DOC:   x y z   vector values
    'DOC: Return Value
    'DOC:   a filled Vector3 type
    '-----------------------------------------------------------------------------
    Function vec3(x As Single, y As Single, Z As Single) As Vector3
        Return New Vector3(x, y, Z)
    End Function


    '-----------------------------------------------------------------------------
    'DOC: Vec4
    'DOC: Params
    'DOC:   x y z w  vector values
    'DOC: Return Value
    'DOC:   a filled Vector3 type
    '-----------------------------------------------------------------------------
    Function vec4(x As Single, y As Single, Z As Single, w As Single) As Vector4
        Return New Vector4(x, y, Z, w)
    End Function
	
    Function quat(x As Single, y As Single, Z As Single, w As Single) As Quaternion
        Return New Quaternion(x, y, Z, w)
    End Function
	
	'-----------------------------------------------------------------------------
	'DOC: D3DUtil_RotationAxis
	'DOC: Params
	'DOC:   x y z               axis of rotation
	'DOC:   rotationInDegrees   rotationInDegrees
	'DOC:
	'DOC: Return Value
	'DOC:   a filled D3DQUATERNION type
	'-----------------------------------------------------------------------------
    Function D3DUtil_RotationAxis(x As Single, y As Single, Z As Single, rotationInDegrees As Single) As Quaternion
        '        DxVBLibA.D3DXMATH_QUATERNION.D3DXQuaternionRotationAxis(quat, vec3(x, y, Z), (rotationInDegrees / 180) * g_pi)
        Return Quaternion.RotationAxis(vec3(x, y, Z), (rotationInDegrees / 180) * g_pi)
    End Function
	
	
	
	'-----------------------------------------------------------------------------
	'DOC: D3DUtil_CreateTexture()
	'DOC: Params
	'DOC:   dev     Direct3DDevice  (almost always g_dev)
	'DOC:   strFile name of the file to load
	'DOC:   fmt     prefered format (may be UNKNOWN)
	'DOC: Return Value
	'DOC:   a Direct3DTexture object
	'DOC: Remarks
	'DOC:   Helper function to create a texture. It checks the root path first,
	'DOC:   then tries the media path (as set by setMediaPath)
	'------------------------------------------------------------------------------
	
    Function D3DUtil_CreateTexture(dev As Direct3D9.Device, strFile As String, fmt As Direct3D9.Format) As Direct3D9.Texture
        ' ex ret from vb6 Direct3d9.Texture()

        Try


            Dim strPath As String
            Dim tex As Direct3D9.Texture
            '  Dim tex As Direct3d9.Texture

            strPath = g_mediaPath & strFile
            '  tex = Direct3D9.Texture.FromFile(dev, strPath) ' FG 2014 usare questa se strpath contiene un file dss,che ha gia tutti i parametri 

            tex = Direct3D9.Texture.FromFile(dev, strPath, Direct3D9.Usage.None, Direct3D9.Pool.Default, 0, 0, fmt, Direct3D9.Pool.Managed, Direct3D9.Filter.Default, Direct3D9.Filter.Default, 0)
            ' tex = g_d3dx.CreateTextureFromFileEx(dev, strPath, DxVBLibA.CONST_D3DXENUM.D3DX_DEFAULT, DxVBLibA.CONST_D3DXENUM.D3DX_DEFAULT, DxVBLibA.CONST_D3DXENUM.D3DX_DEFAULT, 0, fmt, DxVBLibA.CONST_D3DPOOL.D3DPOOL_MANAGED, DxVBLibA.CONST_D3DXENUM.D3DX_DEFAULT, DxVBLibA.CONST_D3DXENUM.D3DX_DEFAULT, 0, 0, 0)

            Return tex

        Catch ex As Exception
            Debug.Print("D3DUtil_CreateTexture Error")
            Return Nothing
        End Try


    End Function



    '-----------------------------------------------------------------------------
    'DOC: D3DUtil_CreateTextureInPool()
    'DOC: Params
    'DOC:   dev     Direct3DDevice (all most always g_dev)
    'DOC:   strFile name of the texture to load
    'DOC:   fmt     prefered format (may be UNKNOWN)
    'DOC: Return Value
    'DOC:   a Direct3DTexture object
    'DOC: Remarks
    'DOC:   Helper function to create a texture. It checks the root path first,
    'DOC:   then tries the media path (as set by setMediaPath)
    'DOC:   This function differs from D3DUtil_CreateTexture in that
    'DOC:   Multiple calls with the same texture name will result in
    'DOC:   returning the same texture object
    'DOC:   To release all texture to allow a device change see
    'DOC:   D3DUtil_ReleaseAllTexturesFromPool
    '-----------------------------------------------------------------------------

    Function D3DUtil_CreateTextureInPool(dev As Direct3D9.Device, strFile As String, fmt As Direct3D9.Format) As Direct3D9.Texture




        ' On Error GoTo ErrOut
        Try



            Dim strPath As String
            Dim tex As Direct3D9.Texture

            Dim transcolor As Integer
            Dim miplev As Integer
            Dim filter_Renamed As Integer
            Dim mipfilter As Direct3D9.Filter
            Dim w As Integer
            Dim h As Integer

            If System.IO.File.Exists(strFile) = False Then Return Nothing

            tex = D3DUtil_FindTextureInPool(strFile)
            If tex IsNot Nothing Then
                Return tex
            End If


            strPath = g_mediaPath & strFile


            If Not g_TextureSampling.enable Then
                fmt = Direct3D9.Format.Unknown
                miplev = Direct3D9.Filter.Default 'Direct3D9.DxVBLibA.CONST_D3DXENUM.D3DX_DEFAULT
                filter_Renamed = Direct3D9.Filter.Default '.DxVBLibA.CONST_D3DXENUM.D3DX_DEFAULT
                mipfilter = Direct3D9.Filter.Default
                w = Direct3D9.Filter.Default
                h = Direct3D9.Filter.Default
                transcolor = 0
            Else
                miplev = g_TextureSampling.miplevels
                filter_Renamed = g_TextureSampling.filter_Renamed
                mipfilter = g_TextureSampling.mipfilter
                w = g_TextureSampling.width
                h = g_TextureSampling.height
                fmt = g_TextureSampling.fmt
                transcolor = 0
            End If

            'Check for color keys
            If (InStr(strFile, "_t.") <> 0) And g_TextureSampling.enable Then
                fmt = g_TextureSampling.fmtTrans
                transcolor = g_TextureSampling.colorTrans Or &HFF000000
            End If

            If (InStr(strFile, ".tif") <> 0) Then
                transcolor = 0
                fmt = g_TextureSampling.fmtTrans
            End If


            tex = Direct3D9.Texture.FromFile(dev, strPath, _
                                          w, h, miplev, 0, fmt, Direct3D9.Pool.Managed, filter_Renamed, mipfilter, transcolor)

            D3DUtil_AddTextureToPool(tex, strFile)

            Return tex

        Catch ex As Exception
            Debug.Print("D3DUtil_CreateTextureInPool error")
            Return Nothing
        End Try
    End Function

    '-----------------------------------------------------------------------------
    'DOC: D3DUtil_ReleaseTextureFromPool()
    'DOC: Params
    'DOC:   strFileName name of the texture to release
    '-----------------------------------------------------------------------------

    Sub D3DUtil_ReleaseTextureFromPool(strFileName As String)
        Dim i As Integer
        For i = 0 To m_nextEmpty - 1
            If (m_texPool(i).Name = strFileName) Then
                m_texPool(i).nextDelNode = m_firstDel
                m_firstDel = i
                m_texPool(i).Name = ""
                Discard(m_texPool(i).tex)
                Return
            End If
        Next
    End Sub

    Sub Discard(ByRef o As Object)
        Try
            If o IsNot Nothing Then o.dispose()
            o = Nothing
        Catch ex As Exception
            o = Nothing
        End Try
    End Sub
    '-----------------------------------------------------------------------------
    'DOC: D3DUtil_FindTextureInPool
    'DOC: Params
    'DOC:   strFileName name of the texture to release
    'DOC: Return value
    'DOC:   texture that was found or Nothing if name not found
    'DOC:   Will return the first match. Is case sensitive
    '-----------------------------------------------------------------------------

    Function D3DUtil_FindTextureInPool(strFileName As String) As Direct3D9.Texture
        Dim i As Integer
        For i = 0 To m_nextEmpty - 1
            If (m_texPool(i).Name = strFileName) Then Return m_texPool(i).tex
        Next
        Return Nothing
    End Function


    '-----------------------------------------------------------------------------
    'DOC: D3DUtil_ReleaseAllTexturesFromPool()
    'DOC: Remarks
    'DOC:   Release all textures from the pool
    'DOC:   This is required before attempting to completely release a device
    'DOC:   as the device still exists until all objects created from it
    'DOC:   are also released or set to Nothing
    '-----------------------------------------------------------------------------

    Sub D3DUtil_ReleaseAllTexturesFromPool()
        Try
            For Each o As TexPoolEntry In m_texPool
                Discard(o.tex)
            Next
        Catch ex As Exception
        End Try
        ReDim m_texPool(0)
        m_firstDel = -1
        m_nextEmpty = 0
        m_maxPool = 0
    End Sub

    '-----------------------------------------------------------------------------
    'DOC: D3DUtil_AddTextureToPool
    'DOC: Params
    'DOC:   tex         Direct3DTexture to add
    'DOC:   strFile     name to associate with texture
    'DOC: Remarks
    'DOC:   Be aware that the Texture pool names are case sensitive
    '-----------------------------------------------------------------------------

    Function D3DUtil_AddTextureToPool(tex As Direct3D9.Texture, strFile As String) As Boolean

        'If the list is empty - makeit
        If m_maxPool = 0 Then
            ReDim m_texPool(kGrowSize)
            m_maxPool = kGrowSize
            m_firstDel = -1
            m_texPool(0).tex = tex
            m_texPool(0).Name = strFile
            m_texPool(0).nextDelNode = -1
            Return True
        End If

        'If there are items that are deleted then
        'use there slots
        If m_firstDel > -1 Then
            m_texPool(m_firstDel).tex = tex
            m_texPool(m_firstDel).Name = strFile
            m_firstDel = m_texPool(m_firstDel).nextDelNode
            m_texPool(m_firstDel).nextDelNode = -1
            Return True
        End If

        'If there are no slots left create a slot
        If m_maxPool <= m_nextEmpty Then
            m_maxPool = m_maxPool + kGrowSize
            ReDim Preserve m_texPool(m_maxPool)
        End If

        'assign the entry to the next available slot
        m_texPool(m_nextEmpty).tex = tex
        m_texPool(m_nextEmpty).Name = strFile
        m_texPool(m_nextEmpty).nextDelNode = -1
        m_nextEmpty = m_nextEmpty + 1

        Return True

    End Function

    '-----------------------------------------------------------------------------
    'DOC: D3DUtil_SetTextureLoadCallback
    'DOC:
    'DOC: Params
    'DOC:   obj     can equal nothing to remove the callback from use
    'DOC:           or an object that implements
    'DOC:           LoadTextureCallback(sName as string) as Direct3dTexture8
    'DOC:
    '-----------------------------------------------------------------------------
    Sub D3DUtil_SetTextureLoadCallback(ByRef obj As Object)
        g_TextureLoadCallback = obj

        g_bUseTextureLoadCallback = False
        If obj Is Nothing Then Return

        g_bUseTextureLoadCallback = True
    End Sub


    '-----------------------------------------------------------------------------
    'DOC: D3DUtil_SetTextureSampling
    'DOC:
    'DOC: Params
    'DOC:      bEnable     Enable/Disable sampling defaults
    'DOC:      w           default width for all textures
    'DOC:      h           default height for all texture
    'DOC:      levels      default number of miplevels
    'DOC:      fmt         default texture format
    'DOC:      transfmt    default texture format for alpha textures
    'DOC:      transcolor  transparent color to mask for textures with file names
    'DOC:                  ending in xxxx_t.bmp or xxxx_t.yyy
    '-----------------------------------------------------------------------------
    Sub D3DUtil_SetTextureSampling(bEnable As Boolean, w As Integer, h As Integer, levels As Integer, fmt As Direct3D9.Format, transfmt As Direct3D9.Format, transcolor As Integer)
        With g_TextureSampling
            .enable = bEnable
            .width = w
            .height = h
            .miplevels = levels
            .mipfilter = Direct3D9.Filter.Box 'DxVBLibA.CONST_D3DXENUM.D3DX_FILTER_BOX
            .filter_Renamed = Direct3D9.Filter.Box 'DxVBLibA.CONST_D3DXENUM.D3DX_FILTER_BOX
            .fmt = fmt
            .colorTrans = transcolor
            .fmtTrans = transfmt
        End With
    End Sub
	
	
	
	'-----------------------------------------------------------------------------
	'DOC: D3DUtil_CreateFrame
	'DOC:
	'DOC: Params:
	'DOC:       parent      Parent whos child is the returned frame
	'DOC:                   can be Nothing
	'DOC:
	'DOC: Returns
	'DOC:       New Frame object
	'-----------------------------------------------------------------------------
	Function D3DUtil_CreateFrame(ByRef parent As CD3DFrame) As CD3DFrame
        Dim f As New CD3DFrame
        If parent Is Nothing Then Return Nothing
        parent.AddChild(f)
        Return f
	End Function
	
	
	'-----------------------------------------------------------------------------
	' Name: D3DUtil_LoadFromFile
	'-----------------------------------------------------------------------------
    Function D3DUtil_LoadFromFile(strFile As String, parentFrame As CD3DFrame, parentAnimation As CD3DAnimation) As CD3DFrame
        Try

      
        Dim newFrame As CD3DFrame
        newFrame = New CD3DFrame

        g_bLoadSkins = False
        newFrame.InitFromFile(g_dev, strFile, parentFrame, parentAnimation)


        'CONSIDER the need to set the FVF on load.
        newFrame.SetFVF(g_dev, D3DFVF_VERTEX)
            Return newFrame

        Catch ex As Exception
            Debug.Print("D3DUtil_LoadFromFile error: " & ex.Message)
            Return Nothing
        End Try
    End Function
	
	
	'-----------------------------------------------------------------------------
	' Name: D3DUtil_LoadFromFileAsSkin
	'-----------------------------------------------------------------------------
    Function D3DUtil_LoadFromFileAsSkin(strFile As String, parentFrame As CD3DFrame, parentAnimation As CD3DAnimation) As CD3DFrame
        Try


            Dim newFrame As CD3DFrame
            newFrame = New CD3DFrame
            g_bLoadSkins = True
            newFrame.InitFromFile(g_dev, strFile, parentFrame, parentAnimation)
            newFrame.AttatchBonesToMesh(newFrame)
            Return newFrame

        Catch ex As Exception
            Debug.Print("D3DUtil_LoadFromFileAsSkin error: " & ex.Message)
            Return Nothing
        End Try
    End Function
	
	
	'-----------------------------------------------------------------------------
	' Name: D3DUtil_LoadFromFileAsMesh
	'-----------------------------------------------------------------------------
    Function D3DUtil_LoadFromFileAsMesh(strFile As String) As CD3DMesh
        Try
            Dim NewMesh As New CD3DMesh
            NewMesh.InitFromFile(g_dev, strFile)
            NewMesh.SetFVF(g_dev, D3DFVF_VERTEX)
            Return NewMesh

        Catch ex As Exception
            Debug.Print("D3DUtil_LoadFromFileAsSkin error: " & ex.Message)
            Return Nothing
        End Try
    End Function
	
	'-----------------------------------------------------------------------------
	' Name: D3DUtil_SetMediaPath
	'-----------------------------------------------------------------------------
    Sub D3DUtil_SetMediaPath(path As String)
        g_mediaPath = path
    End Sub
	
	
	
	'-----------------------------------------------------------------------------
	' Name: D3DUtil_InitLight
	'-----------------------------------------------------------------------------
    Sub D3DUtil_InitLight(ByRef lgt As Direct3D9.Light, ty As Direct3D9.LightType, x As Single, y As Single, Z As Single)
        lgt.Type = ty
        lgt.Diffuse = ColorValue4(1, 1, 1, 1)
        lgt.Attenuation1 = 0.01
        lgt.Attenuation0 = 0
        lgt.Attenuation2 = 0
        lgt.Range = 99999999
        lgt.Direction = New Vector3(x, y, Z)
        lgt.Position = New Vector3(x, y, Z)
         
    End Sub
	
	
	'-----------------------------------------------------------------------------
	' Name: D3DUtil_ComputeClipPlanes
	'-----------------------------------------------------------------------------
    Sub D3DUtil_ComputeClipPlanes(ByRef veye As Vector3, vat As Vector3, vUp As Vector3, fov As Single, front As Single, back As Single, aspect As Single)

        Dim vDir As New Vector3
        Dim vright As New Vector3

        Dim vFrontCenter As New Vector3
        Dim vFrontUp As New Vector3
        Dim vFrontRight As New Vector3

        Dim vBackCenter As New Vector3

        Dim vBackRight As New Vector3
        Dim vbackLeft As New Vector3

        Dim vBackRightTop As New Vector3
        Dim vBackLeftTop As New Vector3

        Dim vBackRightBot As New Vector3
        Dim vBackLeftBot As New Vector3

        Dim dx As Single
        Dim dy As Single

        'Establish our basis vector
        vDir = vat - veye
        vDir.Normalize()
        vUp.Normalize()
        vright = Vector3.Cross(vDir, vUp)

        'DxVBLibA.D3DXMATH_VECTOR3.D3DXVec3Subtract(vDir, vat, veye)
        'DxVBLibA.D3DXMATH_VECTOR3.D3DXVec3Normalize(vDir, vDir)
        'DxVBLibA.D3DXMATH_VECTOR3.D3DXVec3Normalize(vUp, vUp)
        'DxVBLibA.D3DXMATH_VECTOR3.D3DXVec3Cross(vright, vDir, vUp)

        dx = System.Math.Tan(fov / 2) * back
        dy = dx * aspect

        '
        '
        '              /|  vbackleft (top,bot)
        '             / |
        '        vfront |
        '           /|  |
        '       eye ----|  vbackcenter
        '           \|  |
        '            \  |dx
        '             \ |
        '              \|  vbackright (top,bot)
        '
        '


        'compute vbackcenter
        'DxVBLibA.D3DXMATH_VECTOR3.D3DXVec3Scale(vBackCenter, vDir, back)
        'DxVBLibA.D3DXMATH_VECTOR3.D3DXVec3Add(vBackCenter, vBackCenter, veye)

        vBackCenter = vDir * back
        vBackCenter = vBackCenter + veye

        'compute vbackright
        'DxVBLibA.D3DXMATH_VECTOR3.D3DXVec3Scale(vBackRight, vright, dx)
        'DxVBLibA.D3DXMATH_VECTOR3.D3DXVec3Add(vBackRight, vBackCenter, vBackRight)

        vBackRight = vright * dx
        vBackRight = vBackCenter + vBackRight


        'compute vbackleft
        'DxVBLibA.D3DXMATH_VECTOR3.D3DXVec3Scale(vbackLeft, vright, -dx)
        'DxVBLibA.D3DXMATH_VECTOR3.D3DXVec3Add(vbackLeft, vBackCenter, vbackLeft)

        vbackLeft = vright * -dx
        vbackLeft = vBackCenter + vbackLeft


        'compute vbackrighttop
        'DxVBLibA.D3DXMATH_VECTOR3.D3DXVec3Scale(vBackRightTop, vUp, dy)
        'DxVBLibA.D3DXMATH_VECTOR3.D3DXVec3Add(vBackRightTop, vBackRight, vBackRightTop)

        vBackRightTop = vUp * dx
        vBackRightTop = vBackRightTop + vBackRight


        'compute vbacklefttop
        'DxVBLibA.D3DXMATH_VECTOR3.D3DXVec3Scale(vBackLeftTop, vUp, dy)
        'DxVBLibA.D3DXMATH_VECTOR3.D3DXVec3Add(vBackLeftTop, vBackRight, vBackLeftTop)
        vBackLeftTop = vUp * dy
        vBackLeftTop = vBackLeftTop + vBackRight

        'compute vbackrightbot
        'DxVBLibA.D3DXMATH_VECTOR3.D3DXVec3Scale(vBackRightBot, vUp, -dy)
        'DxVBLibA.D3DXMATH_VECTOR3.D3DXVec3Add(vBackRightBot, vBackRight, vBackRightBot)
        vBackRightBot = vUp * -dy
        vBackRightBot = vBackRightBot + vBackRight


        'compute vbackleftbot
        'DxVBLibA.D3DXMATH_VECTOR3.D3DXVec3Scale(vBackLeftBot, vUp, -dy)
        'DxVBLibA.D3DXMATH_VECTOR3.D3DXVec3Add(vBackLeftBot, vBackRight, vBackLeftBot)
        vBackLeftBot = vUp * -dy
        vBackLeftBot = vBackLeftBot + vBackRight


        'compute vfrontcenter
        'DxVBLibA.D3DXMATH_VECTOR3.D3DXVec3Scale(vFrontCenter, vDir, front)
        'DxVBLibA.D3DXMATH_VECTOR3.D3DXVec3Add(vFrontCenter, vFrontCenter, veye)
        vFrontCenter = vDir * front
        vFrontCenter = vFrontCenter + veye



        'compute vfrontright
        'DxVBLibA.D3DXMATH_VECTOR3.D3DXVec3Scale(vFrontRight, vright, dx)
        'DxVBLibA.D3DXMATH_VECTOR3.D3DXVec3Add(vFrontRight, vFrontCenter, vFrontRight)
        vFrontRight = vright * dx
        vFrontRight = vFrontCenter + vFrontRight

        'compute vfrontup
        'DxVBLibA.D3DXMATH_VECTOR3.D3DXVec3Scale(vFrontUp, vUp, dy)
        'DxVBLibA.D3DXMATH_VECTOR3.D3DXVec3Add(vFrontUp, vFrontCenter, vFrontUp)
        vFrontUp = vUp * dy
        vFrontUp = vFrontCenter + vFrontUp


        ReDim g_ClipPlanes(6)
        g_numClipPlanes = 6



        'front plane
        'DxVBLibA.D3DXMATH_PLANE.D3DXPlaneFromPointNormal(g_ClipPlanes(0), veye, vDir)
        g_ClipPlanes(0) = New Plane(veye, vDir)






        'back plane
        Dim vnegdir As New Vector3
        'DxVBLibA.D3DXMATH_VECTOR3.D3DXVec3Scale(vnegdir, vDir, -1)
        'DxVBLibA.D3DXMATH_PLANE.D3DXPlaneFromPointNormal(g_ClipPlanes(1), vBackCenter, vnegdir)
        vnegdir = Vector3.Multiply(vDir, -1)
        g_ClipPlanes(1) = New Plane(vBackCenter, vnegdir)



        'right plane
        ' DxVBLibA.D3DXMATH_PLANE.D3DXPlaneFromPoints(g_ClipPlanes(2), veye, vBackRightTop, vBackRightBot)
        g_ClipPlanes(2) = New Plane(veye, vBackRightTop, vBackRightBot)

        'left plane
        '  DxVBLibA.D3DXMATH_PLANE.D3DXPlaneFromPoints(g_ClipPlanes(3), veye, vBackLeftTop, vBackLeftBot)
        g_ClipPlanes(3) = New Plane(veye, vBackLeftTop, vBackLeftBot)

        'top plane
        ' DxVBLibA.D3DXMATH_PLANE.D3DXPlaneFromPoints(g_ClipPlanes(4), veye, vBackLeftTop, vBackRightTop)
        g_ClipPlanes(4) = New Plane(veye, vBackLeftTop, vBackRightTop)

        'bot plane
        ' DxVBLibA.D3DXMATH_PLANE.D3DXPlaneFromPoints(g_ClipPlanes(5), veye, vBackRightBot, vBackLeftBot)
        g_ClipPlanes(5) = New Plane(veye, vBackRightBot, vBackLeftBot)

        g_numClipPlanes = 4

    End Sub
	
	
	'-----------------------------------------------------------------------------
	'DOC: D3DUtil_IntersectTriangleCull
	'DOC: Params
	'DOC:   v0,v1,v2    points from a triangle
	'DOC:   vDir        direction vector of a ray to intersect triangle
	'DOC:   vOrig       origen of ray to interesect triangle
	'DOC:   t           distance from origen to intersection
	'DOC:   u,v         u v coordinates of intersection
	'DOC: Return value
	'DOC:   true if intersected, false if not
	'DOC:
	'DOC: See CD3DPick object if intersecting a ray with a mesh or frame
	'-----------------------------------------------------------------------------
	
    Function D3DUtil_IntersectTriangleCull(ByRef v0 As Vector3, ByRef v1 As Vector3, ByRef v2 As Vector3, ByRef vDir As Vector3, ByRef vOrig As Vector3, ByRef t As Single, ByRef u As Single, ByRef v As Single) As Boolean

        Dim edge1 As New Vector3
        Dim edge2 As New Vector3
        Dim pvec As New Vector3
        Dim tvec As New Vector3
        Dim qvec As New Vector3
        Dim Det As Single
        Dim fInvDet As Single

        'find vectors for the two edges sharing vert0

        'DxVBLibA.D3DXMATH_VECTOR3.D3DXVec3Subtract(edge1, v1, v0)
        'DxVBLibA.D3DXMATH_VECTOR3.D3DXVec3Subtract(edge2, v2, v0)
        edge1 = Vector3.Subtract(v1, v0)
        edge2 = Vector3.Subtract(v2, v0)

        'begin calculating the determinant - also used to caclulate u parameter
        '  DxVBLibA.D3DXMATH_VECTOR3.D3DXVec3Cross(pvec, vDir, edge2)
        pvec = Vector3.Cross(vDir, edge2)

        'if determinant is nearly zero, ray lies in plane of triangle
        ' Det = DxVBLibA.D3DXMATH_VECTOR3.D3DXVec3Dot(edge1, pvec)
        Det = Vector3.Dot(edge1, pvec)

        If (Det < 0.0001) Then Return False

        'calculate distance from vert0 to ray origin
        'DxVBLibA.D3DXMATH_VECTOR3.D3DXVec3Subtract(tvec, vOrig, v0)
        tvec = Vector3.Subtract(vOrig, v0)

        'calculate u parameter and test bounds
        'u = DxVBLibA.D3DXMATH_VECTOR3.D3DXVec3Dot(tvec, pvec)
        u = Vector3.Dot(tvec, pvec)
        If (u < 0 Or u > Det) Then Return False

        'prepare to test v parameter
        'DxVBLibA.D3DXMATH_VECTOR3.D3DXVec3Cross(qvec, tvec, edge1)
        pvec = Vector3.Cross(tvec, edge1)

        'calculate v parameter and test bounds
        ' v = DxVBLibA.D3DXMATH_VECTOR3.D3DXVec3Dot(vDir, qvec)
        v = Vector3.Dot(vDir, pvec)
        If (v < 0 Or (u + v > Det)) Then Return False
         
        'calculate t, scale parameters, ray intersects triangle
        '  t = DxVBLibA.D3DXMATH_VECTOR3.D3DXVec3Dot(edge2, qvec)
        t = Vector3.Dot(edge2, qvec)
        fInvDet = 1 / Det
        t = t * fInvDet
        u = u * fInvDet
        v = v * fInvDet
        If t = 0 Then Return False

        Return True

    End Function
	
	
	'-----------------------------------------------------------------------------
	' Name: D3DUtil_IsSphereVisible
	'-----------------------------------------------------------------------------
    Function D3DUtil_IsSphereVisible(SphereCenterInWorldSpace As Vector3, SphereRadius As Single) As Integer

        Dim i As Integer
        Dim dist As Single

        For i = 0 To g_numClipPlanes - 1
            ' dist = DxVBLibA.D3DXMATH_PLANE.D3DXPlaneDotCoord(g_ClipPlanes(i), SphereCenterInWorldSpace)
            dist = Plane.DotCoordinate(g_ClipPlanes(i), SphereCenterInWorldSpace)

            If dist < -1 * SphereRadius Then
                'sphere is completely behind the plane
                'if its behind any plane then its clipped
                 
                Return 0

            End If
        Next

        Return 1

    End Function
	
	
	
	'-----------------------------------------------------------------------------
	' Name: D3DPLANE4
	'-----------------------------------------------------------------------------
    Function D3DPLANE4(a As Single, b As Single, c As Single, d As Single) As Plane
        Return New Plane(a, b, c, d)
    End Function
	
	'-----------------------------------------------------------------------------
	' Name: FtoDW
	'
	' For calls that require that a single be packed into a long
	' (such as some calls to SetRenderState) this function will do just that
	'-----------------------------------------------------------------------------
    Function FtoDW(f As Single) As Integer
        ' FG non trovo SlimDx Wrappers validi
        'Dim buf As Buffer ' DxVBLibA.D3DXBuffer
        'Dim l As Integer
        'buf = g_d3dx.CreateBuffer(4)
        'g_d3dx.BufferSetData(buf, 0, 4, 1, f)
        'g_d3dx.BufferGetData(buf, 0, 4, 1, l)
        'FtoDW = l
    End Function
	
	'-----------------------------------------------------------------------------
	' Name: LONGtoD3DCOLORVALUE
	'-----------------------------------------------------------------------------
    Function LONGtoD3DCOLORVALUE(Color As Integer) As Color4
        Return New Color4(Color)

        'Dim g, a, r, b As Integer

        'If Color < 0 Then
        '    a = (CShort(Color And (&H7F000000)) / 2 ^ 24) Or &H80
        'Else
        '    a = Color / (2 ^ 24)
        'End If
        'r = CShort(Color And &HFF0000) / 2 ^ 16
        'g = CShort(Color And &HFF00) / 2 ^ 8
        'b = (Color And &HFF)

        'LONGtoD3DCOLORVALUE.a = a / 255
        'LONGtoD3DCOLORVALUE.r = r / 255
        'LONGtoD3DCOLORVALUE.g = g / 255
        'LONGtoD3DCOLORVALUE.b = b / 255

    End Function
	
	
	'-----------------------------------------------------------------------------
	' Name: D3DCOLORVALUEtoLONG
	'-----------------------------------------------------------------------------
	
    Function D3DCOLORVALUEtoLONG(cv As Color4) As Integer
        Return cv.ToArgb

        'Dim r As Integer
        'Dim g As Integer
        'Dim b As Integer
        'Dim a As Integer
        'Dim c As Integer

        'r = cv.r * 255
        'g = cv.g * 255
        'b = cv.b * 255
        'a = cv.a * 255

        'If a > 127 Then
        '    a = a - 128
        '    c = a * 2 ^ 24 Or &H80000000
        '    c = c Or r * 2 ^ 16
        '    c = c Or g * 2 ^ 8
        '    c = c Or b
        'Else
        '    c = a * 2 ^ 24
        '    c = c Or r * 2 ^ 16
        '    c = c Or g * 2 ^ 8
        '    c = c Or b
        'End If

        'D3DCOLORVALUEtoLONG = c
    End Function
	
    '----------------------------------------------------------------------------- 
	' Name: DXUtil_Timer()
	' Desc: Performs timer opertations. Use the following commands:
	'          TIMER_RESET           - to reset the timer
	'          TIMER_START           - to start the timer
	'          TIMER_STOP            - to stop (or pause) the timer
	'          TIMER_ADVANCE         - to advance the timer by 0.1 seconds
	'          TIMER_GETABSOLUTETIME - to get the absolute system time
	'          TIMER_GETAPPTIME      - to get the current time
	'          TIMER_GETELLAPSEDTIME - to get the ellapsed time between calls
	'-----------------------------------------------------------------------------
	Function DXUtil_Timer(ByRef command_Renamed As TIMER_COMMAND) As Single
		
		On Error Resume Next
		
		Static m_bTimerInitialized As Boolean
		Static m_bUsingQPF As Boolean
		Static m_fSecsPerTick As Single
		Static m_fBaseTime As Single
		Static m_fStopTime As Single
		Static m_fLastTime As Single
		
		Dim fTime As Single
		
		' Initialize the timer
		If (False = m_bTimerInitialized) Then
			m_bTimerInitialized = True
		End If
		
		fTime = VB.Timer()
		
		' Reset the timer
		If (command_Renamed = TIMER_COMMAND.TIMER_RESET) Then
			m_fBaseTime = fTime
			m_fStopTime = 0
			m_fLastTime = 0
            DXUtil_Timer = 0
            On Error GoTo 0
			Exit Function
		End If
		
		' Return the current time
		If (command_Renamed = TIMER_COMMAND.TIMER_GETAPPTIME) Then
            DXUtil_Timer = fTime - m_fBaseTime
            On Error GoTo 0
			Exit Function
		End If
		
		' Start the timer
		If (command_Renamed = TIMER_COMMAND.TIMER_START) Then
			m_fBaseTime = m_fBaseTime + fTime - m_fStopTime
			m_fLastTime = m_fLastTime + fTime - m_fStopTime
			m_fStopTime = 0
		End If
		
		' Stop the timer
		If (command_Renamed = TIMER_COMMAND.TIMER_STOP) Then
			m_fStopTime = fTime
		End If
		
		' Advance the timer by 1/10th second
		If (command_Renamed = TIMER_COMMAND.TIMER_ADVANCE) Then
			m_fBaseTime = m_fBaseTime + fTime - (m_fStopTime + 0.1)
		End If
		
		
		' Return ellapsed time
		If (command_Renamed = TIMER_COMMAND.TIMER_GETELLAPSEDTIME) Then
			DXUtil_Timer = fTime - m_fLastTime
			m_fLastTime = fTime
            If DXUtil_Timer < 0 Then DXUtil_Timer = 0
            On Error GoTo 0
			Exit Function
		End If
		
        On Error GoTo 0
		DXUtil_Timer = fTime
    End Function


End Module

